package com.settlement.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.settlement.system.common.base.IBaseEnum;
import com.settlement.system.common.constant.SystemConstants;
import com.settlement.system.common.enums.OMSOrderTypeEnum;
import com.settlement.system.common.util.StringUtils;
import com.settlement.system.mapper.SysOrderDetailMapper;
import com.settlement.system.model.entity.SysOrderDetail;
import com.settlement.system.model.entity.SysStore;
import com.settlement.system.model.form.SysOrderDetailForm;
import com.settlement.system.model.query.SysOrderDetailQuery;
import com.settlement.system.model.vo.SysOrderDetailImportVo;
import com.settlement.system.model.vo.SysOrderDetailVo;
import com.settlement.system.service.SysOrderDetailService;
import com.settlement.system.service.SysStoreService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 标准订单明细 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2024-04-23
 */
@Service
@RequiredArgsConstructor
public class SysOrderDetailServiceImpl extends ServiceImpl<SysOrderDetailMapper, SysOrderDetail> implements SysOrderDetailService {

    private final RedisTemplate redisTemplate;

    private final SysStoreService sysStoreService;

    @Override
    public Page<SysOrderDetailVo> getPage(SysOrderDetailQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        // 拼接月份列表
        List<String> monthList = new ArrayList<>();
        String endMonthStr = queryParams.getEndMonth().replaceAll("-", "");
        LocalDate endMonth = LocalDate.parse(endMonthStr + "01", DateTimeFormatter.ofPattern("yyyyMMdd"));
        LocalDate startTime = LocalDate.parse(queryParams.getStartMonth().replaceAll("-", "") + "01", DateTimeFormatter.ofPattern(
                "yyyyMMdd"));
        // 获取已经生成的表名
        Object object = redisTemplate.opsForValue().get(SystemConstants.ORDER_DETAIL_KEY);
        List<String> tableNameList;
        if (object != null) {
            tableNameList = (List<String>) object;
        } else {
            tableNameList = this.baseMapper.getAllTable();
            // 添加缓存
            redisTemplate.opsForValue().set(SystemConstants.ORDER_DETAIL_KEY, tableNameList, 1, TimeUnit.HOURS);
        }
        // 循环追加月份
        while (!startTime.isAfter(endMonth)) {
            monthList.add(startTime.format(DateTimeFormatter.ofPattern("yyyyMM")));
            startTime = startTime.plusMonths(1);
        }
        // 根据月份判断数据库表是否存在
        List<String> existTableList = new ArrayList<>();
        String tableName;
        for (String month : monthList) {
            tableName = "sys_order_detail_%s".formatted(month);
            if (tableNameList.contains(tableName)) {
                existTableList.add(tableName);
            }
        }
        queryParams.setTableNameList(existTableList);
        // 查询数据
        Page<SysOrderDetail> page = new Page<>(pageNum, pageSize);
        Page<SysOrderDetailVo> voPage = new Page<>(pageNum, pageSize);
        if(existTableList.size() == 0){
            return voPage;
        }
        Page<SysOrderDetail> mapperPage = this.baseMapper.getPage(page, queryParams);
        BeanUtils.copyProperties(page, voPage, "records");
        SysStore sysStore;
        List<SysOrderDetailVo> voList = new ArrayList<>();
        SysOrderDetailVo vo;
        List<String> idList = mapperPage.getRecords().stream().map(SysOrderDetail::getLinkId).filter(StringUtils::hasText).distinct().toList();
        List<String> billMonthList = new ArrayList<>();
        for (String billMonth : idList) {
            if(!billMonthList.contains(billMonth.substring(0, 6))){
                billMonthList.add(billMonth.substring(0, 6));
            }
        }
        for (SysOrderDetail record : mapperPage.getRecords()) {
            vo = new SysOrderDetailVo();
            sysStore = sysStoreService.getById(record.getStoreId());
            if (sysStore != null) {
                record.setStoreName(sysStore.getCommercePlatformStoreName());
            }
            if(Objects.equals("Sent", vo.getOrderStatus())){
                vo.setOrderStatus("已发货");
            }
            record.setOrderTypeName(IBaseEnum.getLabelByValue(record.getOrderType(), OMSOrderTypeEnum.class));
            BeanUtils.copyProperties(record, vo);
            voList.add(vo);
        }
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public boolean saveSysOrderDetail(SysOrderDetailForm sysOrderDetailForm) {
        SysOrderDetail sysOrderDetail = new SysOrderDetail();
        BeanUtil.copyProperties(sysOrderDetailForm, sysOrderDetail);
        sysOrderDetail.setCreateTime(null);
        return this.saveOrUpdate(sysOrderDetail);
    }

    @Override
    public SysOrderDetailForm getSysOrderDetailFormData(Long id) {
        SysOrderDetail sysOrderDetail = this.getById(id);
        SysOrderDetailForm sysOrderDetailForm = new SysOrderDetailForm();
        BeanUtil.copyProperties(sysOrderDetail, sysOrderDetailForm);
        return sysOrderDetailForm;
    }

    @Override
    public boolean deleteSysOrderDetail(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的数据为空");
        List<Long> idArray = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        return this.removeByIds(idArray);
    }

    @Override
    public void importData(List<SysOrderDetailImportVo> voList) {
        List<SysOrderDetail> sysOrderDetailList = new ArrayList<>();
        for (SysOrderDetailImportVo importVo : voList) {
            SysOrderDetail sysOrderDetail = new SysOrderDetail();
            BeanUtil.copyProperties(importVo, sysOrderDetail);
            sysOrderDetailList.add(sysOrderDetail);
        }
        this.saveOrUpdateBatch(sysOrderDetailList);
    }

    @Override
    public List<SysOrderDetailImportVo> findByIds(String idsStr) {
        if (StrUtil.isBlank(idsStr)) {
            return new ArrayList<>();
        }
        List<Long> ids = Arrays.stream(idsStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<SysOrderDetail> sysOrderDetailList = this.getBaseMapper().selectBatchIds(ids);
        List<SysOrderDetailImportVo> voList = new ArrayList<>();
        for (SysOrderDetail sysOrderDetail : sysOrderDetailList) {
            SysOrderDetailImportVo vo = new SysOrderDetailImportVo();
            BeanUtil.copyProperties(sysOrderDetail, vo);
            voList.add(vo);
        }
        return voList;
    }
}
